<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Cache;
use think\Config;
use think\Request;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 用户登录
     */
    public function login()
    {
        if(!Request::instance()->isPost()){
            $this->error('请求类型错误');
        }
        $code = $this->request->post('code');
        if(empty($code)){
            $this->error('参数错误');
        }
        $accessToken = Cache::store('redis')->get('wx_access_token');
        if(!$accessToken){
            $accessToken = $this->_getWxAccessToken();
        }
        $userPhone = $this->_getUserPhone($code,$accessToken);
        if(empty($userPhone)){
            $this->error('登录失败');
        }
        $token = $this->_checkUserByPhone($userPhone);
        $this->success('登录成功',['token' => $token]);
    }

    /**
     * 用户信息
    */
    public function userInfo()
    {
        $userInfo = $this->auth->getUserinfo();
        $this->success('用户信息',$userInfo);
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     */
    public function profile()
    {
        if(!Request::instance()->isPost()){
            $this->error('请求类型错误');
        }
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $gender = $this->request->post('gender');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        // 昵称
        $user->nickname = $nickname;
        // 性别
        $user->gender = $gender;
        // 头像
        $user->avatar = $avatar;
        $user->save();
        $this->success('修改成功');
    }


    /**
     * 选择角色
    */
    public function updateGroup()
    {
        if(!Request::instance()->isPost()){
            $this->error('请求类型错误');
        }
        $user = $this->auth->getUser();
        if(!empty($user->group_id)){
            $this->error('您已有角色');
        }
        // 角色ID
        $groupId = $this->request->post('group_id');
        if(empty($groupId)){
            $this->error('请选择角色');
        }
        $user->group_id = $groupId;
        $user->save();
        $this->success('选择成功');
    }

    /**
     * 获取微信accessToken
     */
    private function _getWxAccessToken()
    {
        $appId = config('site.app_id');
        $appSecret = config('site.app_secret');
        $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
        $result = json_decode(request_curl_get($url),true);
        if(isset($result['access_token'])&&!empty($result['access_token'])){
            // 设置缓存
            Cache::store('redis')->set('wx_access_token', $result['access_token'], 7000);
        }
        return $result['access_token'];
    }

    /**
     * 获取小程序用户手机号
     */
    private function _getUserPhone($code,$accessToken)
    {
        $phone = '';
        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$accessToken;
        $param['code'] = $code;
        $result = json_decode(request_url($url,$param),true);
        if($result['errcode']==0&&$result['errmsg']=='ok'){
            $phone = $result['phone_info']['phoneNumber'];
        }
        return $phone;
    }

    /**
     * 检测改手机号是否已存在如果不存在就添加
     */
    private function _checkUserByPhone($phone)
    {
        $userInfo = model('User')->where('mobile',$phone)->find();
        if(!$userInfo){
            $this->auth->register('','','',$phone);
        }else{
            $this->auth->direct($userInfo->id);
        }
        return $this->auth->getToken();
    }
}
